<template>
	<view class="">
		<!-- 弹出层 -->
		<uni-popup ref="popup" :mask-click="false" @maskClick="handleNaskClick()" :animation="false">
			<view class="popup_body">
				<view class="popup_top" @click="handleNaskClick()">
					<view class="popup_top_title">{{ title }}</view>
					<view class="popup_top_count" v-if="type === 'inventoryPlan'">
						<text>共{{ boxCount || 0 }}件有效</text><text>，{{ nSweptBoxCount || 0 }}件未扫</text>
					</view>
					<view class="popup_top_count" v-else>
						<text>共{{ materialList.length || 0 }}件</text></text>
					</view>
					<view class="popup_top_close" @click="close()">
						<i class="iconfont icon-shanchu"></i>
					</view>
				</view>
				<view class="popup_content" @click="handleNaskClick()">
					<uni-loading v-if="loading"></uni-loading>
					<!-- 扫描中 -->
					<view class="popup_content_scaning" v-else-if="isWaitScan">
						<template v-if="isContinuous">
							<textarea id="myTextarea" ref="textareaRef" v-model="scanVal"  :focus="isFocus" :adjust-position="false" @blur="isFocus=false"
								@input="onScanSuccess" placeholder="等待扫描中....."
								placeholder-class="popup_content_scaning_placeholder" maxlength="-1" />
							<!--  底部按钮  -->
							<view class="popup_content_btn">
								<button @click="changeScanningType(false)"
									class="popup_content_btn_item cancel margin_imp">扫码
								</button>
								<button @click="onContinuousScanSuccess()"
									class="popup_content_btn_item submit margin_imp" type="primary">完成
								</button>
							</view>
						</template>
						<template v-else>
							<input v-model="scanVal"  :focus="isFocus" :adjust-position="false" @blur="isFocus=false"
								@confirm="onScanSuccess" placeholder="等待扫码中....."
								placeholder-class="popup_content_scaning_placeholder" />
							<view class="popup_content_btn">
								<button @click="changeScanningType(true)"
									class="popup_content_btn_item submit margin_imp">切换RFID扫描
								</button>
							</view>
						</template>
					</view>
					<!-- 扫描结果 -->
					<block v-else>
						<view class="popup_content_info">
							<scroll-view scroll-y="true" class="popup_content_info_scroll">
								<template v-for="item in materialList">
									<view class="material" :class="{materialSelect: isSelect && item.locationNo === barcodeTypeLocationNo}" @click.stop="handleSelectBC(item.locationNo)">
										<view class="material_title">
											{{ item.materialName }}
										</view>
										<view class="material_row">
											<view class="material_row_item" v-if="item.materialNo">
												<view class="material_row_item_title">
													物料编码：
												</view>
												<view class="material_row_item_value">
													{{ item.materialNo }}
												</view>
											</view>
											<view class="material_row_item">
												<view class="material_row_item_title">
													批次：
												</view>
												<view class="material_row_item_value">
													{{ item.batchNo }}
												</view>
											</view>
											<view class="material_row_item" v-if="isLocation">
												<view class="material_row_item_title">
													仓位：
												</view>
												<view class="material_row_item_value">
													{{ locationNo }}
												</view>
											</view>
											<view class="material_row_item" v-else>
												<view class="material_row_item_title">
													仓位：
												</view>
												<view class="material_row_item_value">
													{{ item.locationNo }}
												</view>
											</view>
											
											<view class="material_row_item" v-if="item.materialNo">
												<view class="material_row_item_title">
													规格：
												</view>
												<view class="material_row_item_value">
													{{ item.materialSpec }}
												</view>
											</view>
											<view class="material_row_item">
												<view class="material_row_item_title">
													单位：
												</view>
												<view class="material_row_item_value">
													{{ item.unit }}
												</view>
											</view>
											
											<view class="material_row_item full_width">
												<view class="material_row_item_title">
													重量：
												</view>
												<view class="material_row_item_input">
													<input type="text"
														:disabled="(!isLocation || type === 'transfer') && item.barcodeType !== 'BC' && type !== 'taskRefund'"
														v-model="item.count" placeholder="请输入物料重量"
														placeholder-class="placeholder_class" />
												</view>
											</view>
										</view>
									</view>
								</template>
							</scroll-view>
						</view>
						<!--  底部按钮  -->
						<view class="popup_content_btn">
							<button @click="close()" class="popup_content_btn_item cancel">取消</button>
							<button @click="reset()" class="popup_content_btn_item reset" type="warning">重新扫码</button>
							<button @click="submit()" class="popup_content_btn_item submit" type="primary">添加</button>
						</view>
					</block>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
	import UniLoading from "../../vBase/components/uni-loading/uni-loading.vue"

	export default {
		components: {
			UniLoading
		},
		props: {
			title: {
				type: String,
				default: ""
			},
			type: {
				type: String,
				default: ""
			},
			isLocation: {
				type: Boolean,
				default: true
			},
			defaultStock: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				loading: false,
				isWaitScan: true,
				isFocus: false,
				scanVal: null,
				stockNo: null,
				locationNo: null,
				materialList: [],
				scanValList: [],
				isContinuous: false, // 是否为连续扫码
				billNo: null,
				taskBillNo: null,
				orderId: null,   // 
				scanValLength: 0, // 已扫入的箱号数量
				boxCount: 0, // 有效箱数
				nSweptBoxCount: 0, // 未扫箱数
				noBatch: true,
				isSelect: false,
				barcodeTypeLocationNo: null,
				apiList: {
					purchase: {
						rfid: 'getMaterialByRfid',
						box: 'getMaterialByBox',
						add: 'addUserPurinMaterialBoxList'
					},
					warehousing: {
						rfid: 'getMaterialByRfidPrdCol',
						box: 'getMaterialByBoxProCol',
						add: 'addUserPrdinMaterialBoxList'
					},
					picking: {
						rfid: 'getMaterialByRfidInStock',
						box: 'getInventoryMaterialByBox',
						add: 'addUserPrdpickMaterialBoxList'
					},
					saleOut: {
						rfid: 'getMaterialByRfidInStock',
						box: 'getInventoryMaterialByBox',
						add: 'addUserSaleoutMaterialBoxList'
					},
					inStock: {
						rfid: 'getMaterialByRfidOtherCol',
						box: 'getMaterialByBoxCol',
						add: 'addUserOtherInMaterialBoxList'
					},
					outStock: {
						rfid: 'getMaterialByRfidInStock',
						box: 'getInventoryMaterialByBox',
						add: 'addUserOtheroutMaterialBoxList'
					},
					inventoryPlan: {
						rfid: 'getStockTakeMaterialByRfidInStock',
						box: 'getStockTakeMaterialByBox',
						add: 'addUserTaskDetailBoxList'
					},
					transfer: {
						rfid: 'getUserAllocationRfid',
						box: 'getUserAllocationBoxList',
						add: 'addUserAllocationBoxList'
					},
					transferEdit: {
						rfid: 'getTaskAllocatioBoxRfid',
						box: 'getTaskAllocationBox',
						add: 'rfidAddTaskAllocationBox'
					},
					tray: {
						rfid: 'getMaterialRfidNoTray',
						box: 'getMaterialBoxNoTray',
						add: 'addTrayBox'
					},
					taskPicking: {
						rfid: 'getMaterialByRfidInStock',
						box: 'getMaterialBomBox',
						add: 'addMaterialBomBox'
					},
					taskFill: {
						rfid: 'getMaterialByRfidInStock',
						box: 'getMaterialBomBox',
						add: 'addMaterialBomSupplementBox'
					},
					taskRefund: {
						rfid: 'getProduceReturnRfid',
						box: 'getProduceReturnBox',
						add: 'addMaterialBomBoxReturn'
					},
					taskInStork: {
						rfid: 'prdInScanRfid',
						box: 'prdInScanBoxNo',
						add: 'addPrdInBoxList'
					},
				},
			}
		},
		watch: {
			scanValLength() {
				this.getRfidCount()
			},
			isContinuous(val) {
				if (val) {
					this.$nextTick(() => {
						document.getElementById('myTextarea').addEventListener('mouseup', this.setCursorPosition);
					})
				} else {
					document.getElementById('myTextarea').removeEventListener('mouseup', this.setCursorPosition);
				}
			}
		},
		methods: {
			setCursorPosition(e) {
				const position = e.target.selectionStart
				if (position < e.target.value.length) {
					var myDiv = document.getElementById("myTextarea");
					var myTextAreas = myDiv.querySelectorAll("textarea");
					if (myTextAreas.length) {
						myTextAreas[0].selectionStart = e.target.value.length
						myTextAreas[0].selectionEnd = e.target.value.length
					}
				}
			},

			/**
			 * 打开面板
			 */
			open(stockNo, locationNo = null, billNo = null, taskBillNo = null, orderId = null) {
				if (!stockNo && this.defaultStock) {
					uni.showToast({
						title: '请选择仓库',
						icon: 'none'
					});
					return;
				}
				if (this.isLocation && !locationNo && this.defaultStock) {
					uni.showToast({
						title: '请选择仓位',
						icon: 'none'
					});
					return;
				}
				let self = this
				// 初始化参数
				this.reset()
				this.stockNo = stockNo;
				this.locationNo = locationNo;
				this.billNo = billNo;
				this.orderId = orderId;
				this.taskBillNo = taskBillNo;
				this.$refs.popup.open('bottom')
				// #ifdef APP-PLUS
				plus.key.addEventListener('keydown', event => {
					self.isFocus = true
				});
				// #endif
				this.boxCount = 0 // 有效箱数
				this.nSweptBoxCount = 0 // 未扫箱数
				
				// this.$nextTick(() => {
				// 	document.getElementById('myTextarea').addEventListener('mouseup', this.setCursorPosition);
				// })
			},

			/**
			 * 关闭面板
			 */
			close() {
				this.$refs.popup.close()
				this.isFocus = false
			},

			/**
			 * 重新扫码
			 */
			reset() {
				this.scanVal = null
				this.scanValLength = 0
				this.isWaitScan = true
				this.loading = false
				this.materialList = []
				this.$nextTick(() => {
					this.isFocus = true
				})
			},

			/**
			 * 连续扫码完成
			 */
			async onContinuousScanSuccess() {
				try {
					let self = this
					if (!self.scanVal) {
						uni.showToast({
							title: "请扫描物料信息",
							icon: "none"
						})
						return
					}
					self.loading = true
					self.isFocus = false
					let rfidList = self.scanVal.split('\n')
					rfidList = rfidList.filter(item => {
						return item !== ""
					})
					let params = {
						rfid: rfidList,
						stockNo: self.stockNo,
					}
					if (self.type === 'inventoryPlan') {
						params.locationNo = self.locationNo
						params.billNo = self.billNo
					}
					if (self.type === 'taskRefund' || self.type === 'taskInStork') {
						delete params.rfid
						delete params.stockNo
						params.rfidList = rfidList
						params.billNo = self.taskBillNo
					}
					let res = await self.$api[this.apiList[self.type].rfid](params)
					self.loading = false
					if (!res.res) return
					if ((res.data && res.data.length === 0)) {
						uni.showToast({
							title: "没有查到物料信息",
							icon: "none"
						})
						self.scanVal = null
						self.scanValLength = 0
						self.isFocus = true
						// 错误提示音
						self.handleMediaPlayer('error')
						// this.handleVibrate(2, 500)
						return
					}
					self.handleMediaPlayer('success')
					self.materialList = res.data
					self.isWaitScan = false
					self.scanVal = null
					self.scanValLength = 0
				} catch (e) {
					// 错误提示音
					this.handleMediaPlayer('error')
					// this.handleVibrate(2, 500)
				}
			},

			/**
			 * 监听扫码结果
			 * @param e
			 */
			async onScanSuccess(e) {
				let self = this
				if (self.isContinuous) {
					// 扫一个响一次
					this.handleMediaPlayer('success')
					if (self.scanVal) {
						setTimeout(() => {
							let rfidList = self.scanVal.split('\n')
							for (let i = rfidList.length - 1; i >= 0; i--) {
								if (!rfidList[i]) continue;
								if (rfidList.indexOf(rfidList[i]) < i) {
									rfidList.splice(i, 1)
								}
							}
							self.scanValLength = JSON.parse(JSON.stringify(rfidList)).length
							let newVal = rfidList.join("\n")
							self.scanVal = newVal
							self.loading = false
						}, 10)
					}
				} else {
					if (self.loading) return
					try {
						self.loading = true
						self.isFocus = false
						let param = self.isLocation ? {
							boxNo: self.scanVal
						} : {
							stockNo: self.stockNo,
							boxNo: self.scanVal
						}
						if (self.type === 'inventoryPlan') {
							param.stockNo = self.stockNo
							param.locationNo = self.locationNo
							param.billNo = self.billNo
							let resBox = await this.$api.getBoxNoCount({
								boxNoList: [self.scanVal],
								locationNo: self.locationNo,
								billNo: self.billNo
							});
							if (!resBox.res) return
							this.boxCount = resBox.boxCount
							this.nSweptBoxCount = resBox.nSweptBoxCount
						}
						if (self.type === 'transfer') {
							param.stockNo = self.stockNo,
							param.locationNo = self.locationNo
						}
						if (self.type === 'taskPicking' || self.type === 'taskFill') param.billNo = self.billNo
						if (self.type === 'taskRefund' || self.type === 'taskInStork') param.billNo = self.taskBillNo
						if (param.boxNo && param.boxNo.startsWith('T')) {
							uni.setStorageSync("transfer", param.boxNo)
						} else {
							uni.removeStorageSync("transfer")
						}
						let res = await self.$api[self.apiList[self.type].box](param, {
							dialog: !self.isContinuous
						});
						if (!res.res) {
							self.loading = false
							return
						};
						if (self.type === 'taskPicking' || self.type === 'taskFill') {
							if (res.hasOwnProperty('noBatch')) {
								self.noBatch = res.noBatch
							}
						}
						this.materialList = res.hasOwnProperty('data') ? res.data : [res];
						if (this.materialList && this.materialList.length && self.type !== 'taskRefund' && this
							.materialList[0].barcodeType !== 'BC') {
							this.submit(false, true)
							return
						}
						// 扫码成功之后会有成功提示（如果直接submit，就先不提示）
						self.handleMediaPlayer('success')
						// 如果是包材数据
						if (this.materialList[0].barcodeType === 'BC') {
							// 变成可选择
							this.isSelect = true
							this.barcodeTypeLocationNo = this.materialList[0].locationNo
						}
						self.loading = false
						self.isWaitScan = false
					} catch (e) {
						// 错误提示音
						self.handleMediaPlayer('error')
						// this.handleVibrate(2, 500)
					} finally {
						self.loading = false
						self.scanVal = null
						self.scanValLength = 0
						this.$nextTick(() => {
							self.isFocus = true
						})
					}
				}
			},

			/**
			 * 立即入库
			 */
			async submit(close = true, tone = false) {
				const {
					stockNo,
					locationNo,
					isLocation
				} = this;
				let materialListCopy = JSON.parse(JSON.stringify(this.materialList))
				if (!materialListCopy.length) {
					uni.showToast({
						title: `请添加物料`,
						icon: 'none'
					});
					return;
				}
				try {
					this.loading = true
					let material = materialListCopy.find(item => !item.count || item.count <= 0)
					if (material) {
						uni.showToast({
							title: `请输入物料[${material.materialName}]重量`,
							icon: 'none'
						});
						return;
					}
					
					// 如果是包材的数据
					if (this.isSelect) {
						materialListCopy = materialListCopy.filter(v => {
							return v.locationNo === this.barcodeTypeLocationNo
						})
					}
					
					let boxNo = materialListCopy[0].boxNo
					let count = materialListCopy[0].count

					// 判断是否选择仓位
					let param = isLocation ? {
						stockNo,
						locationNo,
					} : {
						stockNo,
					}

					param = Object.assign(param, {
						boxList: materialListCopy
					})
					if (this.type === 'inventoryPlan') {
						param.locationNo = this.locationNo
						param.billNo = this.billNo
					}
					if (this.type === 'transfer') {
						param.stockNo = materialListCopy[0].stockNo
						param.locationNo = materialListCopy[0].locationNo
						param.boxNo = materialListCopy[0].boxNo
						param.materialNo = materialListCopy[0].materialNo
						param.materialName = materialListCopy[0].materialName
						param.materialSpec = materialListCopy[0].materialSpec
						param.batchNo = materialListCopy[0].batchNo
						param.unit = materialListCopy[0].unit
						param.count = materialListCopy[0].count
						param.exp = materialListCopy[0].exp
						param.produceDate = materialListCopy[0].produceDate
						param.rfid = materialListCopy[0].rfid,
						param.allocationType = 'pda'
					}
					if (this.type === 'tray') {
						param = {
							boxList: materialListCopy
						}
					}
					if (this.type === 'taskPicking' || this.type === 'taskFill' || this.type === 'taskRefund') {
						param.billNo = this.orderId
						param.taskBillNo = this.taskBillNo
						param.materialBomBillNo = this.billNo
					}
					if (this.type === 'taskInStork') param.billNo = this.taskBillNo
					// 其他出库-在已创建好的订单进行修改时 在原有参数上多传一个billNo，新建时参数不变
					if (this.type === 'outStock' && this.orderId) param.billNo = this.orderId
					// console.log("param", param)
					let res = await this.$api[this.apiList[this.type].add](param, {
						dialog: !this.isContinuous
					});
					if (!res.res) return;
					// rfid点击添加，关闭弹窗，扫码不需要关闭
					if (close) {
						this.close();
					}
					if (!this.noBatch) {
						uni.showToast({
							title: "添加成功,扫描的箱号不是所选批次",
							icon: "none"
						})
					} else {
						uni.showToast({
							title: `添加成功`,
							icon: 'none'
						});
					}
					// 直接添加的情况，这里成功之后有提示音，手动点击提交的时候是不需要提示音
					if (tone) {
						this.handleMediaPlayer('success')
					}
					this.$emit("success")
				} catch (e) {
					if (e?.data?.err && "箱号已入库!" !== e?.data?.err) {
						this.handleMediaPlayer('error')
					}
				} finally {
					this.loading = false
					this.isFocus = true
				}
			},

			/**
			 * 查询有效rfid数量
			 */
			getRfidCount() {
				if (this.type !== 'inventoryPlan') return
				const self = this
				let currentList = self.scanVal.split('\n').filter(item => {
					return item !== ""
				})
				self.$api.getRfidCount({
					rfidList: currentList,
					billNo: self.billNo,
					locationNo: self.locationNo
				}).then(res => {
					if (res.res) {
						this.boxCount = res.boxCount
						this.nSweptBoxCount = res.nSweptBoxCount
					}
				})
			},

			/** 切换扫描方式 */
			changeScanningType(boo) {
				this.isContinuous = boo
				this.scanVal = null
				this.scanValLength = 0
				this.boxCount = 0
				this.nSweptBoxCount = 0
				this.reset()
			},
			
			/**
			 * @description 选择包材
			 * @param {Object} e
			 */
			handleSelectBC(e) {
				this.barcodeTypeLocationNo = e
			},
			
			/**
			 * 点击扫码框之外
			 */
			handleNaskClick() {
				this.isWaitScan = true
				this.loading = false
				this.$nextTick(() => {
					this.isFocus = true
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	@import "../../static/css/common";

	.popup_body {
		height: 80vh;
	}

	.margin_imp {
		margin: 10px 5px !important;
	}
	
	.materialSelect {
		box-shadow: 0 0 0 2px inset $primary !important;
	}
</style>
